<template>
  <disclosure as="nav" class="bg-gray-800" v-slot="{ open }">
    <div class="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
      <div class="flex h-16 items-center justify-between">
        <div class="flex items-center">
          <div class="flex-shrink-0">
            <img
              class="w-24"
              src="@/assets/images/login-company-logo.png"
              alt="Your Company"
            />
          </div>
          <div class="hidden md:block">
            <div class="ml-10 flex">
              <el-menu
                :default-active="activeIndex"
                class="bg-transparent border-b-0 h-[36px] w-[595px]"
                mode="horizontal"
                @select="handleSelect"
              >
                <el-menu-item
                  id="overview-button"
                  class="el-menu-navigation"
                  index="/"
                  >{{ $t('appPageTitle.overview') }}
                </el-menu-item>
                <el-sub-menu
                  index="/system-management"
                  class="*:el-menu-navigation"
                >
                  <template #title>
                    {{ $t('appNavigation.systemManagement') }}
                  </template>
                  <el-menu-item
                    v-for="(info, i) in headerNavigation.systemManagement"
                    :key="i"
                    :index="info.path"
                  >
                    {{ info.meta.title }}
                  </el-menu-item>
                </el-sub-menu>
                <el-sub-menu index="/diagnostic" class="*:el-menu-navigation">
                  <template #title>{{
                    $t('appNavigation.diagnostic')
                  }}</template>
                  <el-menu-item
                    v-for="(info, i) in headerNavigation.diagnostic"
                    :key="i"
                    :index="info.path"
                    >{{ info.meta.title }}</el-menu-item
                  >
                </el-sub-menu>
                <el-sub-menu
                  index="/user-security"
                  class="*:el-menu-navigation"
                >
                  <template #title>{{
                    $t('appNavigation.UserSecurity')
                  }}</template>
                  <el-menu-item
                    v-for="(info, i) in headerNavigation.userSecurity"
                    :key="i"
                    :index="info.path"
                    >{{ info.meta.title }}</el-menu-item
                  >
                </el-sub-menu>
                <el-sub-menu index="/services" class="*:el-menu-navigation">
                  <template #title>{{ $t('appNavigation.Services') }}</template>
                  <el-menu-item
                    v-for="(info, i) in filteredNavigation(
                      headerNavigation.services,
                    )"
                    :key="i"
                    :index="info.path"
                    >{{ info.meta.title }}</el-menu-item
                  >
                </el-sub-menu>
                <el-sub-menu index="/settings" class="*:el-menu-navigation">
                  <template #title>{{ $t('appNavigation.settings') }}</template>
                  <el-menu-item
                    v-for="(info, i) in headerNavigation.settings"
                    :key="i"
                    :index="info.path"
                    >{{ info.meta.title }}</el-menu-item
                  >
                </el-sub-menu>
              </el-menu>
            </div>
          </div>
        </div>
        <div class="hidden md:block">
          <div class="ml-4 flex items-center md:ml-6 *:mx-2">
            <el-popover
              v-for="(item, key, index) in buttonArrays"
              :key="index"
              placement="bottom"
              :title="item.title"
              trigger="hover"
              :content="item.content"
            >
              <template #reference>
                <component
                  :is="item.component"
                  :params="item.params.length > 0 ? item.params[0] : ''"
                />
              </template>
            </el-popover>

            <!-- Profile dropdown -->
            <menu-main as="div" class="relative ml-3">
              <el-popover
                placement="bottom"
                trigger="hover"
                :content="globalStore.username"
              >
                <template #reference>
                  <div>
                    <menu-button class="header-button">
                      <span class="absolute -inset-1.5" />
                      <span class="sr-only">Open user menu</span>
                      <user-circle-icon class="h-8 w-8" />
                    </menu-button>
                  </div>
                </template>
              </el-popover>
              <transition
                enter-active-class="transition ease-out duration-100"
                enter-from-class="transform opacity-0 scale-95"
                enter-to-class="transform opacity-100 scale-100"
                leave-active-class="transition ease-in duration-75"
                leave-from-class="transform opacity-100 scale-100"
                leave-to-class="transform opacity-0 scale-95"
              >
                <menu-items
                  class="absolute right-0 z-10 mt-2 w-48 origin-top-right rounded-md bg-white py-1 shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none"
                >
                  <menu-item
                    v-for="item in userNavigation"
                    :key="item.name"
                    v-slot="{ active }"
                  >
                    <a
                      :class="[
                        active ? 'bg-gray-100' : '',
                        'block px-4 py-2 text-sm text-gray-700',
                        'cursor-pointer',
                      ]"
                      @click="item.action"
                    >
                      {{ item.name }}
                    </a>
                  </menu-item>
                </menu-items>
              </transition>
            </menu-main>
          </div>
        </div>
        <div class="mr-2 flex md:hidden">
          <!-- Mobile menu button -->
          <disclosure-button
            class="relative inline-flex items-center justify-center rounded-md bg-gray-800 p-2 text-gray-400 hover:bg-gray-700 hover:text-white focus:outline-none focus:ring-2 focus:ring-white focus:ring-offset-2 focus:ring-offset-gray-800"
          >
            <span class="absolute -inset-0.5" />
            <span class="sr-only">Open main menu</span>
            <bars3-icon v-if="!open" class="block h-6 w-6" aria-hidden="true" />
            <x-mark-icon v-else class="block h-6 w-6" aria-hidden="true" />
          </disclosure-button>
        </div>
      </div>
    </div>

    <disclosure-panel class="md:hidden">
      <div class="space-y-1 px-2 pb-3 pt-2 sm:px-3">
        <el-menu
          :default-active="activeIndex"
          class="bg-transparent border-b-0 h-[36px] w-[595px]"
          mode="horizontal"
          @select="handleSelect"
        >
          <el-menu-item
            id="overview-button"
            class="el-menu-navigation"
            index="/"
            >{{ $t('appPageTitle.overview') }}
          </el-menu-item>
          <el-sub-menu index="/system-management" class="*:el-menu-navigation">
            <template #title>
              {{ $t('appNavigation.systemManagement') }}
            </template>
            <el-menu-item
              v-for="(info, i) in headerNavigation.systemManagement"
              :key="i"
              :index="info.path"
            >
              {{ info.meta.title }}
            </el-menu-item>
          </el-sub-menu>
          <el-sub-menu index="/diagnostic" class="*:el-menu-navigation">
            <template #title>{{ $t('appNavigation.diagnostic') }}</template>
            <el-menu-item
              v-for="(info, i) in headerNavigation.diagnostic"
              :key="i"
              :index="info.path"
              >{{ info.meta.title }}</el-menu-item
            >
          </el-sub-menu>
          <el-sub-menu index="/user-security" class="*:el-menu-navigation">
            <template #title>{{ $t('appNavigation.UserSecurity') }}</template>
            <el-menu-item
              v-for="(info, i) in headerNavigation.userSecurity"
              :key="i"
              :index="info.path"
              >{{ info.meta.title }}</el-menu-item
            >
          </el-sub-menu>
          <el-sub-menu index="/services" class="*:el-menu-navigation">
            <template #title>{{ $t('appNavigation.Services') }}</template>
            <el-menu-item
              v-for="(info, i) in filteredNavigation(headerNavigation.services)"
              :key="i"
              :index="info.path"
              >{{ info.meta.title }}</el-menu-item
            >
          </el-sub-menu>
          <el-sub-menu index="/settings" class="*:el-menu-navigation">
            <template #title>{{ $t('appNavigation.settings') }}</template>
            <el-menu-item
              v-for="(info, i) in headerNavigation.settings"
              :key="i"
              :index="info.path"
              >{{ info.meta.title }}</el-menu-item
            >
          </el-sub-menu>
        </el-menu>
      </div>
      <div class="border-t border-gray-700 pb-3 pt-4">
        <div class="flex items-center px-5">
          <div class="flex-shrink-0">
            <user-circle-icon class="h-10 w-10 header-button" />
          </div>
          <div class="ml-3 mr-auto">
            <div class="text-base font-medium leading-none text-white">
              {{ user.name }}
            </div>
          </div>
          <el-popover
            v-for="(item, key, index) in buttonArrays"
            :key="index"
            placement="bottom"
            :title="item.title"
            trigger="hover"
            :content="item.content"
          >
            <template #reference>
              <component
                :is="item.component"
                :params="item.params.length > 0 ? item.params[0] : ''"
              />
            </template>
          </el-popover>
        </div>
        <div class="mt-3 space-y-1 px-2">
          <disclosure-button
            v-for="item in userNavigation"
            :key="item.name"
            class="block rounded-md px-3 py-2 text-base font-medium text-gray-400 hover:bg-gray-700 hover:text-white hover:cursor-pointer"
            @click="item.action"
            >{{ item.name }}</disclosure-button
          >
        </div>
      </div>
    </disclosure-panel>
  </disclosure>
</template>

<script setup lang="ts">
import {
  Disclosure,
  DisclosureButton,
  DisclosurePanel,
  Menu as MenuMain,
  MenuButton,
  MenuItem,
  MenuItems,
} from '@headlessui/vue';
import {
  Bars3Icon,
  XMarkIcon,
  UserCircleIcon,
} from '@heroicons/vue/24/outline';
import HeaderNavigation, { type NavItemType } from './HeaderNavigation';
import languageButton from './iconButton/LanguageButton.vue';
import refreshButton from './iconButton/RefreshButton.vue';
import powerButton from './iconButton/PowerButton.vue';
import healthButton from './iconButton/HealthButton.vue';
import helpButton from './iconButton/HelpButton.vue';
import { useAuthenticationStore } from '@/store/Authentication/Authentication';
import { useEventLogStore } from '@/store/Diagnostic/EventLog/EventLogStore';
import { useGlobalStore } from '@/store/global';
import { useI18n } from 'vue-i18n';

const $router = reactive(useRouter());
const headerNavigation = computed(() => HeaderNavigation() as any);
const currentUserRole = ref();
const globalStore = useGlobalStore();
const i18n = reactive(useI18n());
const authenticationStore = useAuthenticationStore();
const eventLogStore = useEventLogStore();

const user = computed(() => {
  return {
    name: globalStore.username,
  };
});

const buttonArrays = computed(() => {
  return {
    healthButton: {
      title: i18n.t('appHeader.health'),
      content: '',
      component: healthButton,
      params: [healthStatusIcon.value],
    },
    powerButton: {
      title: i18n.t('appHeader.power'),
      content: '',
      component: powerButton,
      params: [serverStatusIcon.value],
    },
    refreshButton: {
      title: i18n.t('appHeader.refresh'),
      content: '',
      component: refreshButton,
      params: [],
    },
    languageButton: {
      title: i18n.t('appHeader.currentLanguage'),
      content: i18n.t('appHeader.languageContent'),
      component: languageButton,
      params: [],
    },
    helpButton: {
      title: i18n.t('appHeader.help'),
      content: '',
      component: helpButton,
      params: [healthStatusIcon.value],
    },
  };
});

const serverStatus = computed(() => globalStore.serverStatus);
const healthStatus = computed(() => eventLogStore.healthStatus);

const healthStatusIcon = computed(() => {
  switch (healthStatus.value) {
    case 'OK':
      return 'success';
    case 'Warning':
      return 'warning';
    case 'Critical':
      return 'danger';
    default:
      return 'secondary';
  }
});

const serverStatusIcon = computed(() => {
  switch (serverStatus.value) {
    case 'on':
      return 'success';
    case 'error':
      return 'danger';
    case 'diagnosticMode':
      return 'warning';
    default:
      return 'secondary';
  }
});

const userNavigation = computed(() => [
  {
    name: i18n.t('appHeader.profileSettings'),
    action: () => {
      $router.push('/profile-settings');
    },
  },
  {
    name: i18n.t('appHeader.logOut'),
    action: () => {
      authenticationStore.logout();
    },
  },
]);

const activeIndex = computed(() => {
  return $router.currentRoute.path;
});

const handleSelect = (key: string) => {
  $router.push(key);
};

const getPrivilege = () => {
  currentUserRole.value = globalStore.userPrivilege;
};

const filteredNavigation = (navigation: NavItemType[]) => {
  if (currentUserRole.value) {
    return navigation.filter((item) => {
      if (item.meta.exclusiveToRoles) {
        return item.meta.exclusiveToRoles!.includes(currentUserRole.value);
      } else return true;
    });
  } else return navigation;
};

const getSystemInfo = () => {
  globalStore.getSystemInfo();
};
const getEvents = () => {
  eventLogStore.getEventLogData();
};

onMounted(() => {
  getPrivilege();
  getSystemInfo();
  getEvents();
});
</script>
